//
//  RBLoginVC.m
//  LittlePig
//
//  Created by Riber on 6/8/18.
//  Copyright © 2018年 Riber. All rights reserved.
//

#import "RBLoginVC.h"
#import "RBRegistVC.h"
#import "Tabbar_VC.h"
#import <BmobSDK/BmobQuery.h>
#import <BmobSDK/BmobObject.h>

#define MaxCount 12

@interface RBLoginVC () <UITextFieldDelegate>

@property (nonatomic,   weak) UIScrollView      *mainSV;

@property (nonatomic, strong) UIImageView       *logoIV;
@property (nonatomic, strong) UITextField   *mobileTF;
@property (nonatomic, strong) UITextField   *passTF;
@property (nonatomic, strong) UIButton          *loginBtn;
@property (nonatomic, strong) UIButton          *forgotBtn;
@property (nonatomic, strong) UIButton          *registerBtn;
@property (nonatomic, strong) UIButton          *changeLanBtn;


@end

@implementation RBLoginVC

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:self.passTF];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.backItemHidden = YES;
    
    [self createUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBarHidden = NO;
}

#pragma mark mainSV的创建------------
- (UIScrollView *)mainSV {
    if (!_mainSV) {
        UIScrollView *mainSV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
        [self.view addSubview:mainSV];
        mainSV.contentSize = CGSizeMake(self.view.width, self.view.height);
        [mainSV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsZero);
        }];
        //        _mainSV.delegate = self;
        mainSV.showsVerticalScrollIndicator = NO;
        mainSV.showsHorizontalScrollIndicator = NO;
        
        _mainSV = mainSV;
    }
    return _mainSV;
}

- (void)createUI
{
    [self mainSV];
    
    self.logoIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, KHeight(280/2), KWidth(360/2), KHeight(120/2))];
    self.logoIV.centerX = self.view.centerX;
    self.logoIV.image = RBImageNamed(@"logo");
    [self.mainSV addSubview:self.logoIV];
    
    self.mobileTF = [self createTextFieldWithFrame:CGRectMake(KWidth(124/2), self.logoIV.maxY + KHeight(190/2), kSCREENW - KWidth(124), KHeight(88/2)) leftText:@"手机号"];
    self.mobileTF.placeholder = @"请输入手机号";
    self.mobileTF.keyboardType = UIKeyboardTypeDecimalPad;
    self.mobileTF.returnKeyType = UIReturnKeyNext;
    self.mobileTF.delegate = self;
    [self.mobileTF setValue:[UIFont systemFontOfSize:KHeight(15)] forKeyPath:@"_placeholderLabel.font"];
    [self.mobileTF setValue:[UIColor colorWithRed:0.41 green:0.41 blue:0.41 alpha:1.00] forKeyPath:@"_placeholderLabel.textColor"];
    [self.mainSV addSubview:self.mobileTF];
    
    
    self.passTF = [self createTextFieldWithFrame:CGRectMake(self.mobileTF.x, self.mobileTF.maxY + KHeight(30/2), self.mobileTF.width, self.mobileTF.height) leftText:@"密  码"];
    self.passTF.placeholder = @"请输入密码";
    self.passTF.delegate = self;
    self.passTF.secureTextEntry = YES;
    self.passTF.returnKeyType = UIReturnKeyGo;
    [self.passTF setValue:[UIFont systemFontOfSize:KHeight(15)] forKeyPath:@"_placeholderLabel.font"];
    [self.passTF setValue:[UIColor colorWithRed:0.41 green:0.41 blue:0.41 alpha:1.00] forKeyPath:@"_placeholderLabel.textColor"];
    [self.mainSV addSubview:self.passTF];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:self.passTF];
    
    self.loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.passTF.x, self.passTF.maxY + KHeight(50/2), self.passTF.width, KHeight(90/2))];
    [self.loginBtn setBackgroundColor:[UIColor whiteColor]];
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    self.loginBtn.layer.cornerRadius = KHeight(4);
    [self.loginBtn setTitleColor:[UIColor colorWithRed:0.20 green:0.20 blue:0.20 alpha:1.00] forState:UIControlStateNormal];
    [self.loginBtn addTarget:self action:@selector(loginBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.mainSV addSubview:self.loginBtn];
    
    self.forgotBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.loginBtn.x - KWidth(10), self.loginBtn.maxY + KHeight(80/2), self.loginBtn.width / 2 + KWidth(10), KHeight(36/2))];
    [self.forgotBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    self.forgotBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    self.forgotBtn.titleLabel.font = [UIFont systemFontOfSize:KHeight(16)];
    [self.forgotBtn addTarget:self action:@selector(forgotBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.mainSV addSubview:self.forgotBtn];
    
    self.registerBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.loginBtn.maxX - self.loginBtn.width / 2 + KWidth(10), self.forgotBtn.y, self.loginBtn.width / 2 + KWidth(10), self.forgotBtn.height)];
    [self.registerBtn setTitle:@"快速注册" forState:UIControlStateNormal];
    self.registerBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentRight;
    self.registerBtn.titleLabel.font = [UIFont systemFontOfSize:KHeight(16)];
    [self.registerBtn addTarget:self action:@selector(registerBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.mainSV addSubview:self.registerBtn];
    
    self.mobileTF.text = @"17602115326";
    self.passTF.text = @"123456";
    
    
}


- (UITextField *)createTextFieldWithFrame:(CGRect)frame leftText:(NSString *)leftText
{
    UITextField *tf = [[UITextField alloc] initWithFrame:frame];
    tf.leftViewMode = UITextFieldViewModeAlways;
    tf.font = [UIFont systemFontOfSize:KWidth(16)];
    tf.textColor = [UIColor whiteColor];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth(160/2), tf.height)];
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KWidth(150/2), leftView.height)];
    leftLabel.text = leftText;
    leftLabel.numberOfLines = 0;
    leftLabel.lineBreakMode = NSLineBreakByWordWrapping;
    leftLabel.font = [UIFont systemFontOfSize:KHeight(16)];
    leftLabel.textColor = [UIColor whiteColor];
    leftLabel.adjustsFontSizeToFitWidth = YES;
    [leftView addSubview:leftLabel];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, tf.height - 1, tf.width, 1)];
    line.backgroundColor = LINECOLOR;
    [tf addSubview:line];
    
    return tf;
}

- (void)loginBtnClicked:(UIButton *)btn
{
    __weak typeof(self) weakSelf = self;
    if ([self.mobileTF.text length] == 0) {
        [MBProgressHUD showText:@"请输入手机号" toView:self.view];
        return;
    }
    
    if (![Helper justMobile:self.mobileTF.text]) {
        [MBProgressHUD showText:@"手机号码格式有误" toView:self.view];
        return;
    }
    
    if ([self.passTF.text length] == 0) {
        [MBProgressHUD showText:@"请输入密码" toView:self.view];
        return;
    }
    if ([self.passTF.text length] < 6) {
        [MBProgressHUD showText:@"请输入不少于6位或超过12位的密码" toView:self.view];
        return;
    }
    [MBProgressHUD showMessage:@"正在登录..." toView:self.view];
    
    BmobQuery *query = [BmobQuery queryWithClassName:@"UserPerson"];
    [query whereKey:@"phone" equalTo:self.mobileTF.text];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if (!error) {
            if (array.count > 0) {
                BmobObject *object = [array firstObject];
                if ([[object objectForKey:@"psw"] isEqualToString:weakSelf.passTF.text]) {
                    [MBProgressHUD showText:@"登录成功" toView:self.view];
                    [UIApplication sharedApplication].keyWindow.rootViewController = [[Tabbar_VC alloc] init];
                } else {
                    [MBProgressHUD showText:@"密码或手机号填写错误，请重新尝试" toView:self.view];
                }
            } else {
                [MBProgressHUD showText:@"您还没有注册，请先注册" toView:[UIApplication sharedApplication].keyWindow];
                [weakSelf registerBtnClicked:weakSelf.registerBtn];
            }
        } else {
            [MBProgressHUD showText:@"登录失败,请稍后尝试" toView:self.view];
        }
    }];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [MBProgressHUD hideHUDForView:self.view];
//        [MBProgressHUD showText:@"登录成功" toView:self.view];
//
//        [UIApplication sharedApplication].keyWindow.rootViewController = [[Tabbar_VC alloc] init];
//    });
    
}

- (void)forgotBtnClicked:(UIButton *)btn
{

}

- (void)registerBtnClicked:(UIButton *)btn
{
    __weak typeof(self) weakSelf = self;
    RBRegistVC *registVC = [[RBRegistVC alloc] init];
    if ([Helper justMobile:self.mobileTF.text]) {
        registVC.registerMobilStr = self.mobileTF.text;
    }
    [self.navigationController pushViewController:registVC animated:YES];
    registVC.loginBlock = ^(NSString *mobilStr) {
        weakSelf.mobileTF.text = mobilStr;
    };
}

- (void)backButtonClick:(UIButton *)backButton {
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.mobileTF) {
        [self.mobileTF resignFirstResponder];
        [self.passTF becomeFirstResponder];
    }
    else if (textField == self.passTF) {
        [self.passTF resignFirstResponder];
        
        [self loginBtnClicked:nil];
    }
    
    return YES;
}

- (void)textFieldDidChange:(NSNotification *)notification {
    UITextField *passTF = notification.object;
    NSString *toBeString = passTF.text;
    if (toBeString.length > MaxCount) {
        passTF.text = [toBeString substringToIndex:MaxCount];
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}



@end
